const { sequelize } = require('../models');

// 定义一个全局变量，用于保存当前res响应

let clients = new Set();

/**
 * 初始化订单统计数据流
 * @param res
 * @param req
 * */

function initOrderStream(res, req) {
    // 设置event-stream响应头
    res.setHeader('Content-type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    // 将当前客户端响应对象res，赋值给全局变量clients
    clients.add(res);

    // 处理客户端断开连接
    req.on('close', () => {
        // res.send() // 处理响应结束
        clients.delete(res)
    })
}

/**
 * 广播订单数据
 * @returns {Promise<void>}
 * */
async function broadcastOrderCount() {
    const [result] = await sequelize.query(
        "SELECT DATE_FORMAT(`createdAt`, '%y-%m') AS `month`, COUNT(*) AS `value` FROM `Orders` GROUP BY `month` ORDER BY `month` ASC"
    )

    const data = {
        month: [],
        values: [],
    }

    result.forEach(item => {
        data.month.push(item.month);
        data.values.push(item.value)
    });

    // 发送数据给客户端
    clients.forEach(client => {
        client.write(`data: ${JSON.stringify(data)}\n\n`)
    })
}

module.exports = { initOrderStream, broadcastOrderCount }